
package pkg.andru.database;

/**
 * simple create table sql creator.
 * 
 * @author idiottiger
 * @version 1.0
 */
public class SQLTableCreator extends SQLBuilder<SQLTableCreator> {

    static final String TABLE_HEAD = "CREATE TABLE IF NOT EXISTS # ( ID INTEGER PRIMARY KEY AUTOINCREMENT ";

    static final String NOT_NULL = "NOT NULL";

    static final String DEFAULT = "DEFAULT";

    /**
     * set the table name.
     * 
     * @param tableName
     * @return
     */
    public SQLTableCreator setTableName(String tableName) {
        statement.append(TABLE_HEAD.replaceAll("#", tableName));
        return this;
    }

    /**
     * set sql field.
     * 
     * @param name the field' name.
     * @param type must {@link SQLBuilder#TYPE_INT} or
     *            {@link SQLBuilder#TYPE_TEXT} or
     *            {@link SQLBuilder#TYPE_VARCHAR} or
     *            {@link SQLBuilder#TYPE_DATE}.
     * @param length only the type is {@link SQLBuilder#TYPE_VARCHAR}, the
     *            length can used.
     * @param canBeNull
     * @param defaultvalue
     * @return
     */
    public SQLTableCreator setField(String name, String type, int length, boolean canBeNull, String defaultvalue) {
        statement.append(",");
        statement.append(name + " ");
        if (type.equals(TYPE_VARCHAR)) {
            type = TYPE_VARCHAR.replaceFirst("#", String.valueOf(length));
        }
        statement.append(type + " ");
        if (!canBeNull) {
            statement.append(NOT_NULL + " ");
        }
        if (defaultvalue != null) {
            statement.append(DEFAULT + " " + defaultvalue + " ");
        }
        return this;
    }

    /**
     * when build ok, you can reset it, reusing this object.
     */
    public void reset() {
        statement = null;
    }
}
